import store from '@/store/index.js'; // 根据实际情况调整路径

//创建/打开数据库。不存在则创建并打开，存在则打开
function openSqlite(sqlname, sqlpath) {
	console.log(sqlname)
	//这plus.sqlite只在手机APP上运行，记得要在打包模块设置勾选“sqlite”数据库。
	return new Promise((resolve, reject) => {
		plus.sqlite.openDatabase({
			name: sqlname, //数据库名称
			path: sqlpath, //数据库地址，uniapp推荐以下划线为开头
			success(e) {
				IsOpen(sqlname, sqlpath)
			},
			fail(e) {
				IsOpen(sqlname, sqlpath)
			}
		})
	})
}
// 打开数据库失败，查看是否是因为数据库已经打开
function IsOpen(sqlname, sqlpath) {
	let res = plus.sqlite.isOpenDatabase({
		name: sqlname,
		path: sqlpath
	});
	if (res) {
		// console.log(res, '数据库已打开')
		// inquirealltab(sqlname)
		ensureChatListTable(sqlname)
		alltab(sqlname)
	} else {
		console.log(res, '数据库未打开')
	}
}
//查看数据中所有的表
function alltab(sqlname) {

	let sql = "SELECT name FROM sqlite_master WHERE type='table';";
	plus.sqlite.selectSql({
		name: sqlname,
		sql: sql,
		success: function(e) {
			// console.log("查询的结果",e)
		},
		fail: function(e) {
			console.error('创建 chat_list 表失败: ' + JSON.stringify(e));
		}
	});
}

function ensureChatListTable(sqlname) {
	const createTableSQL = `
		          CREATE TABLE IF NOT EXISTS chat_list (
		              receiver_id VARCHAR(32),
		              receiver_avatarBase TEXT, -- 用于存储较长的Base64字符串
		              endmessge VARCHAR(1024),
		              sqlname VARCHAR(32),
		              username VARCHAR(64),
		              endmessgetime VARCHAR(32),
					  islook VARCHAR(32),
		              PRIMARY KEY (receiver_id)
		          );`;

	plus.sqlite.executeSql({
		name: sqlname,
		sql: createTableSQL,
		success: function() {
			getAllData(sqlname)
		},
		fail: function(e) {
			console.error('创建 chat_list 表失败: ' + JSON.stringify(e));
		}
	});
}
// 查询 chat_list 表中的所有数据
async function getAllData(sqlname) {
	return new Promise((resolve) => {
		plus.sqlite.selectSql({
			name: sqlname,
			sql: "SELECT * FROM chat_list ORDER BY endmessgetime DESC;",
			success: function(data) {
				store.commit('setChatList', data);
				resolve();
			},
			fail: function(e) {
				console.error('查询 chat_list 表失败: ' + JSON.stringify(e));
				resolve();
			}
		});
	});
}
// 给chat-list添加数据
// 添加或更新数据到 chat_list 表
async function addOrUpdateChatData(sqlname, sql) {
	try {
		await new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: sqlname,
				sql: sql,
				success: async function(data) {
					try {
						// 等待 getAllData 执行完成
						await getAllData(sqlname);
						resolve(data); // 如果 getAllData 成功，则解析 Promise
					} catch (error) {
						console.error('getAllData failed:', error);
						reject(error); // 如果 getAllData 失败，则拒绝 Promise
					}
				},
				fail: function(e) {
					console.log('selectSql failed: ' + JSON.stringify(e));
					reject(e); // 拒绝 Promise 并传递错误信息
				}
			});
		});
	} catch (error) {
		console.error('addOrUpdateChatData failed:', error);
		throw error; // 重新抛出捕获到的错误，以便调用者可以处理
	}
}

// 删除指定的表
async function delTable(dbName, dbTable) {
	let sql = 'DROP TABLE ' + dbTable + ';'
	return new Promise((resolve) => {
		plus.sqlite.executeSql({
			name: dbName,
			sql: sql,
			success: function(e) {
				resolve();
				console.log("删除数据表成功");
			},
			fail: function(e) {
				resolve();
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		})
	});
}
// 删除chat_list表中指定的数据
// 删除指定的表
async function delchatid(dbName, id) {
	let sql = 'DELETE FROM chat_list WHERE receiver_id = ' + id + ';'
	return new Promise((resolve) => {
		plus.sqlite.executeSql({
			name: dbName,
			sql: sql,
			success: function(e) {
				resolve();
				console.log("chat_list数据删除成功")
				// getAllData(sqlname)
			},
			fail: function(e) {
				resolve();
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		})
	});
}
// 下面的方法：用户接收数据并更新数据表
function receivemess(sokedata) {
	let sql = store.state.chatList
	// console.log(sql, sokedata)
	const foundItem = sql.find(item => item.receiver_id === sokedata.sender_id);
	if (foundItem) {
		Renewalchatlist(sokedata)
	} else {
		appendchatlist(sokedata)
	}
}
// 列表没有这个角色对话
function appendchatlist(sokedata) {
	// 因为更新chat_list方法我使用的是如果有主键为更新，没有则添加，所以在接收并不在列表存在的角色信息只需要在表中添加对话表即可
	let dbTable = `message_${sokedata.sender_id}`
	let sqlitenam = `sqlchat_${store.state.id}`
	let sql = 'CREATE TABLE if not exists ' + dbTable +
		' ( "message_id" varchar(32) NOT NULL,"content" varchar(1024),"sender_id" varchar(32), "receiver_id" varchar(32), "timestamp" varchar(32), PRIMARY KEY ("message_id"));'
	addmesslist(sqlitenam, sql).then((e) => {
		Renewalchatlist(sokedata)
	})

}
// 这是没有存在这个数据对话的

/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                    / _||||| -卍- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 */

// 如果这个列表已经存在这个角色对话那么就更新列表
function Renewalchatlist(sokedata) {
	let chatList = store.state.chatList
	// 获取未读数据的数量
	const targetObject = chatList.find(item => item.receiver_id === sokedata.sender_id);
	const targetValue = targetObject ? targetObject.islook : "no";
	let noLooknum = ''
	if (targetValue == "yse" || targetValue == "NaN" || targetValue == "no") {
		noLooknum = '1'
	} else {
		noLooknum = Number(targetValue) + 1
	}
	// 分为两步，第一步是更新列表
	let sqlitenam = `sqlchat_${store.state.id}`
	let aqlname = `message_${sokedata.sender_id}`
	let sql = "insert or replace into " + 'chat_list' + " values('" + sokedata.sender_id + "','" + sokedata
		.receiver_avatarBase +
		"','" + sokedata.endmessge + "','" + aqlname + "','" + sokedata.username + "','" + sokedata
		.endmessgetime + "','" + noLooknum + "')";
	addOrUpdateChatData(sqlitenam, sql).then((e) => {
		let pushchat = {
			content: sokedata.endmessge,
			message_id: message_id,
			receiver_id: sokedata.receiver_id,
			sender_id: sokedata.sender_id,
			timestamp: sokedata.endmessgetime
		}
		store.commit('setnowchagemess', pushchat);
	})
	//第二步是更新存储数据
	const timestampMs = Date.now();
	const timestampSec = Math.floor(timestampMs / 1000);
	let message_id = timestampSec + sokedata.sender_id
	let dbTable = `message_${sokedata.sender_id}`
	let addListsql = "insert into " + dbTable + " values('" + message_id + "','" + sokedata.endmessge +
		"','" + sokedata.sender_id + "','" + sokedata.receiver_id + "','" + sokedata.endmessgetime + "')";
	addmesslist(sqlitenam, addListsql)
}

async function addmesslist(dbName, sql) {
	plus.sqlite.selectSql({
		name: dbName,
		sql: sql,
		success: function(data) {
			// console.log(data, '---------------')
		},
		fail: function(e) {
			console.log('selectSql failed: ' + JSON.stringify(e));
		}
	});
}
// 此函数是处理用户没有和后端soket连接时，其他用户进入数据发送
async function addnosoket(array) {
	Renewalnuread(array)
	let noreadlength = array.length
	let sokedata = array[noreadlength - 1]
	// /*---------------------更新tab气泡提醒数------------------------------*/
	let int = Number(store.state.messagenum) + noreadlength
	// console.log(int,'应该出现信息提醒',store.state.messagenum)
	// 如果是信息，给消息tab加角标，角标数存储到vuex中，来一条信息加一个角标
	if (int == 0) {
		uni.setTabBarBadge({ //显示数字
			index: 1, //tabbar下标
		})
	} else {
		uni.setTabBarBadge({ //显示数字
			index: 1, //tabbar下标
			text: int > 99 ? '99+' : `${int}` //数字
		})
	}

	store.commit('setmessagenum', int);

	let chatList = store.state.chatList

	// 获取未读数据的数量
	const targetObject = chatList.find(item => item.receiver_id === sokedata.sender_id);
	const targetValue = targetObject ? targetObject.islook : "no";
	let noLooknum = ''
	if (targetValue == "yse" || targetValue == "NaN" || targetValue == "no") {
		noLooknum = noreadlength
	} else {
		noLooknum = Number(targetValue) + noreadlength
	}

	// 分为两步，第一步是更新列表
	let sqlitenam = `sqlchat_${store.state.id}`
	let aqlname = `message_${sokedata.sender_id}`
	let sql = "insert or replace into " + 'chat_list' + " values('" + sokedata.sender_id + "','" + sokedata
		.receiver_avatarBase +
		"','" + sokedata.message + "','" + aqlname + "','" + sokedata.username + "','" + sokedata
		.message_time + "','" + noLooknum + "')";
	addOrUpdateChatData(sqlitenam, sql).then((e) => {
		let pushchat = {
			content: sokedata.endmessge,
			message_id: message_id,
			receiver_id: sokedata.receiver_id,
			sender_id: sokedata.sender_id,
			timestamp: sokedata.endmessgetime
		}
		store.commit('setnowchagemess', pushchat);
	})
}

function Renewalnuread(sokedata) {
	let sqlitenam = `sqlchat_${store.state.id}`
	let sql = store.state.chatList
	const foundItem = sql.find(item => item.receiver_id === sokedata[0].sender_id);
	if (foundItem) {
		sokedata.forEach((item) => { 
			let suij = Math.floor(10000 + Math.random() * 90000)
			const timestampMs = Date.now();
			const timestampSec = Math.floor(timestampMs / 1000);
			let message_id = timestampSec + item.sender_id + suij
			let dbTable = `message_${item.sender_id}`
			let addListsql = "insert into " + dbTable + " values('" + message_id + "','" + item.message +
				"','" + item.sender_id + "','" + item.receiver_id + "','" + getCurrentFormattedDateTime() +
				"')";
			addmesslist(sqlitenam, addListsql)
		})
	} else {
		
		let dbTable = `message_${sokedata[0].sender_id}`
		let sql = 'CREATE TABLE if not exists ' + dbTable +
			' ( "message_id" varchar(32) NOT NULL,"content" varchar(1024),"sender_id" varchar(32), "receiver_id" varchar(32), "timestamp" varchar(32), PRIMARY KEY ("message_id"));'
		addmesslist(sqlitenam, sql).then((e) => {
			sokedata.forEach((item) => {
				let suij = Math.floor(10000 + Math.random() * 90000)
				const timestampMs = Date.now();
				const timestampSec = Math.floor(timestampMs / 1000);
				let message_id = timestampSec + item.sender_id + suij
				let dbTable = `message_${item.sender_id}`
				let addListsql = "insert into " + dbTable + " values('" + message_id + "','" + item
					.message +
					"','" + item.sender_id + "','" + item.receiver_id + "','" +
					getCurrentFormattedDateTime() + "')";
				addmesslist(sqlitenam, addListsql)
			})
		})
	}
}
// 更新未读数据的数据库
//把这些方法导出去
function getCurrentFormattedDateTime() {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，需加1并补0格式化
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');
	const seconds = String(now.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
export default {
	openSqlite,
	IsOpen,
	ensureChatListTable,
	getAllData,
	addOrUpdateChatData,
	delTable,
	delchatid,
	receivemess,
	addnosoket
}